package jnpf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; // 新增导入
import io.swagger.v3.oas.annotations.Operation;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.model.common.ThemeDataReq;
import jnpf.model.page.MyPageInfo;
import jnpf.model.page.MyPageListVO;
import jnpf.model.znm.theme.tree.TreeVO;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.UserService;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.theme.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;

import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.util.stream.Collectors;

import jnpf.onlinedev.model.ExcelImFieldModel;
import jnpf.onlinedev.model.OnlineImport.ImportDataModel;
import jnpf.onlinedev.model.OnlineImport.ImportFormCheckUniqueModel;
import jnpf.onlinedev.model.OnlineImport.ExcelImportModel;
import jnpf.onlinedev.model.OnlineImport.VisualImportModel;
import cn.xuyanwu.spring.file.storage.FileInfo;
import lombok.Cleanup;
import jnpf.model.visualJson.config.HeaderModel;
import jnpf.base.model.ColumnDataModel;
import jnpf.base.util.VisualUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * theme
 *
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-05-08
 */
@Slf4j
@RestController
@Tag(name = "theme", description = "example")
@RequestMapping("/api/example/Theme")
public class ThemeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ThemeService themeService;

    @Autowired
    private ThemeTreeService themeTreeService;


    @Autowired
    private ConfigValueUtil configValueUtil;
    private boolean aBoolean;
    @Autowired
    private ThemeFileService themeFileService;
    @Autowired
    private FileMangeService fileMangeService;

    @Autowired
    private UserService userService;
    @Autowired
    private KnowMangeService knowMangeService;

    @Value("${ragflow.knowUrl}")
    public String KNOW_URL;
    @Autowired
    private ServerUrlUtil serverUrlUtil;


    /**
     * 列表
     *
     * @param themePagination
     * @return
     */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ThemePagination themePagination) throws IOException {
        List<ThemeEntity> list = themeService.getList(themePagination);


        // 过滤掉 isMain 为 0 的 ThemeEntity 对象
        list = list.stream().filter(entity -> entity.getIsmain() != 0).collect(Collectors.toList());
        if(StringUtil.isNotEmpty(themePagination.getContainCreate()) && themePagination.getContainCreate().equals("1")){
            list = list.stream().filter(entity -> StringUtil.isNotEmpty(entity.getVersion())).collect(Collectors.toList());
        }
        List<Map<String, Object>> realList = new ArrayList<>();
        for (ThemeEntity entity : list) {
            Map<String, Object> themeMap = JsonUtil.entityToMap(entity);
            themeMap.put("id", themeMap.get("id"));
            //副表数据
            //子表数据
            List<ThemeTreeEntity> themeTreeList = themeService.getThemeTreeList(entity.getId(), themePagination);
            themeMap.put("tableField116", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(themeTreeList)));
            realList.add(themeMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, ThemeConstant.getFormData(), ThemeConstant.getColumnData(), themePagination.getModuleId(), false);

        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(themePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }

    /**
     * 创建
     *
     * @param themeForm
     * @return
     */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid ThemeForm themeForm) {
        String b = themeService.checkForm(themeForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b);
        }
        try {
            themeService.saveOrUpdate(themeForm, null, true);
        } catch (Exception e) {
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @Operation(summary = "导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ThemePagination themePagination) throws IOException {
        if (StringUtil.isEmpty(themePagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<ThemeEntity> list = themeService.getList(themePagination);
        List<Map<String, Object>> realList = new ArrayList<>();
        for (ThemeEntity entity : list) {
            Map<String, Object> themeMap = JsonUtil.entityToMap(entity);
            themeMap.put("id", themeMap.get("id"));
            //副表数据
            //子表数据
            List<ThemeTreeEntity> themeTreeList = themeService.getThemeTreeList(entity.getId(), themePagination);
            themeMap.put("tableField116", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(themeTreeList)));
            realList.add(themeMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, ThemeConstant.getFormData(), ThemeConstant.getColumnData(), themePagination.getModuleId(), false);
        String[] keys = !StringUtil.isEmpty(themePagination.getSelectKey()) ? themePagination.getSelectKey() : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), realList, keys, userInfo);
        return ActionResult.success(vo);
    }

    /**
     * 导出表格方法
     */
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            ExcelExportEntity tableField116ExcelEntity = new ExcelExportEntity("设计子表", "tableField116");
            List<ExcelExportEntity> tableField116List = new ArrayList<>();
            for (String key : keys) {
                switch (key) {
                    case "themename":
                        entitys.add(new ExcelExportEntity("主题名称", "themename"));
                        break;
                    case "des":
                        entitys.add(new ExcelExportEntity("主题描述", "des"));
                        break;
                    case "themetype":
                        entitys.add(new ExcelExportEntity("主题类型", "themetype"));
                        break;
                    case "belonguser":
                        entitys.add(new ExcelExportEntity("责任人", "belonguser"));
                        break;
                    case "themestatus":
                        entitys.add(new ExcelExportEntity("主题状态", "themestatus"));
                        break;
                    case "version":
                        entitys.add(new ExcelExportEntity("主题版本", "version"));
                        break;
                    case "ismain":
                        entitys.add(new ExcelExportEntity("是否主版本", "ismain"));
                        break;
                    case "lastversion":
                        entitys.add(new ExcelExportEntity("上主题版本", "lastversion"));
                        break;
                    case "createtime":
                        entitys.add(new ExcelExportEntity("创建时间", "createtime"));
                        break;
                    case "createuser":
                        entitys.add(new ExcelExportEntity("创建用户", "createuser"));
                        break;
                    case "updatetime":
                        entitys.add(new ExcelExportEntity("修改时间", "updatetime"));
                        break;
                    case "updateuser":
                        entitys.add(new ExcelExportEntity("更新用户", "updateuser"));
                        break;
                    case "tableField116-name":
                        tableField116List.add(new ExcelExportEntity("主题名称", "name"));
                        break;
                    case "tableField116-themeid":
                        tableField116List.add(new ExcelExportEntity("主题主键", "themeid"));
                        break;
                    case "tableField116-pid":
                        tableField116List.add(new ExcelExportEntity("父主键", "pid"));
                        break;
                    case "tableField116-sort":
                        tableField116List.add(new ExcelExportEntity("该层排序", "sort"));
                        break;
                    default:
                        break;
                }
            }
            if (tableField116List.size() > 0) {
                tableField116ExcelEntity.setList(tableField116List);
                entitys.add(tableField116ExcelEntity);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                //去除空数据
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    int i = 0;
                    for (String key : keys) {
                        //子表
                        if (key.toLowerCase().startsWith("tablefield")) {
                            String tableField = key.substring(0, key.indexOf("-"));
                            String field = key.substring(key.indexOf("-") + 1);
                            Object o = map.get(tableField);
                            if (o != null) {
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) o;
                                for (Map<String, Object> childMap : childList) {
                                    if (childMap.get(field) != null) {
                                        i++;
                                    }
                                }
                            }
                        } else {
                            Object o = map.get(key);
                            if (o != null) {
                                i++;
                            }
                        }
                    }
                    if (i > 0) {
                        dataList.add(map);
                    }
                }
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(ThemeConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList);
                    dataList = VisualUtils.complexHeaderDataHandel(dataList, complexHeaderList);
                }

                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }

    @Operation(summary = "上传文件")
    @PostMapping("/Uploader")
    public ActionResult<Object> Uploader() {
        List<MultipartFile> list = UpUtil.getFileAll();
        MultipartFile file = list.get(0);
        if (file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls")) {
            String filePath = XSSEscape.escape(configValueUtil.getTemporaryFilePath());
            String fileName = XSSEscape.escape(RandomUtil.uuId() + "." + UpUtil.getFileType(file));
            //上传文件
            FileInfo fileInfo = FileUploadUtils.uploadFile(file, filePath, fileName);
            DownloadVO vo = DownloadVO.builder().build();
            vo.setName(fileInfo.getFilename());
            return ActionResult.success(vo);
        } else {
            return ActionResult.fail("选择文件不符合导入");
        }
    }

    /**
     * 模板下载
     *
     * @return
     */
    @Operation(summary = "模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        DownloadVO vo = DownloadVO.builder().build();
        UserInfo userInfo = userProvider.get();
        Map<String, Object> dataMap = new HashMap<>();
        //主表对象
        List<ExcelExportEntity> entitys = new ArrayList<>();
        //以下添加字段
        entitys.add(new ExcelExportEntity("主题版本", "version"));
        entitys.add(new ExcelExportEntity("责任人", "belonguser"));
        dataMap.put("belonguser", "例:张三/账号");
        entitys.add(new ExcelExportEntity("创建时间", "createtime"));
        dataMap.put("createtime", "系统自动生成");
        entitys.add(new ExcelExportEntity("创建用户", "createuser"));
        dataMap.put("createuser", "系统自动生成");
        entitys.add(new ExcelExportEntity("修改时间", "updatetime"));
        dataMap.put("updatetime", "系统自动生成");
        entitys.add(new ExcelExportEntity("更新用户", "updateuser"));
        dataMap.put("updateuser", "系统自动生成");
        entitys.add(new ExcelExportEntity("主题名称", "themename"));
        entitys.add(new ExcelExportEntity("主题类型", "themetype"));
        entitys.add(new ExcelExportEntity("主题状态", "themestatus"));
        //tableField116子表对象
        ExcelExportEntity tableField116ExcelEntity = new ExcelExportEntity("设计子表", "tableField116");
        List<ExcelExportEntity> tableField116ExcelEntityList = new ArrayList<>();
        Map<String, Object> tableField116ChildData = new HashMap<>();
        List<Map<String, Object>> tableField116ChildDataList = new ArrayList<>();
        tableField116ExcelEntityList.add(new ExcelExportEntity("主题名称", "name"));
        tableField116ExcelEntityList.add(new ExcelExportEntity("父主键", "pid"));
        tableField116ExcelEntityList.add(new ExcelExportEntity("该层排序", "sort"));
        tableField116ChildDataList.add(tableField116ChildData);
        dataMap.put("tableField116", tableField116ChildDataList);
        tableField116ExcelEntity.setList(tableField116ExcelEntityList);
        entitys.add(tableField116ExcelEntity);
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(dataMap);

        ExportParams exportParams = new ExportParams(null, "主题管理模板");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(ThemeConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList);
                    list = VisualUtils.complexHeaderDataHandel(list, complexHeaderList);
                }
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String fileName = "主题管理模板" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("模板信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return ActionResult.success(vo);
    }

    /**
     * 导入预览
     *
     * @return
     */
    @Operation(summary = "导入预览")
    @GetMapping("/ImportPreview")
    public ActionResult<Map<String, Object>> ImportPreview(String fileName) throws Exception {
        Map<String, Object> headAndDataMap = new HashMap<>(2);
        String filePath = FileUploadUtils.getLocalBasePath() + configValueUtil.getTemporaryFilePath();
        FileUploadUtils.downLocal(configValueUtil.getTemporaryFilePath(), filePath, fileName);
        File temporary = new File(XSSEscape.escapePath(filePath + fileName));
        int headerRowIndex = 2;
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(headerRowIndex);
        params.setNeedVerify(true);
        try {
            List<ThemeExcelVO> excelDataList = ExcelImportUtil.importExcel(temporary, ThemeExcelVO.class, params);
            // 导入字段
            List<ExcelImFieldModel> columns = new ArrayList<>();
            columns.add(new ExcelImFieldModel("version", "主题版本"));
            columns.add(new ExcelImFieldModel("belonguser", "责任人"));
            columns.add(new ExcelImFieldModel("createtime", "创建时间"));
            columns.add(new ExcelImFieldModel("createuser", "创建用户"));
            columns.add(new ExcelImFieldModel("updatetime", "修改时间"));
            columns.add(new ExcelImFieldModel("updateuser", "更新用户"));
            columns.add(new ExcelImFieldModel("themename", "主题名称"));
            columns.add(new ExcelImFieldModel("themetype", "主题类型"));
            columns.add(new ExcelImFieldModel("themestatus", "主题状态"));
            //tableField116子表对象
            List<ExcelImFieldModel> tableField116columns = new ArrayList<>();
            tableField116columns.add(new ExcelImFieldModel("name", "主题名称"));
            tableField116columns.add(new ExcelImFieldModel("pid", "父主键"));
            tableField116columns.add(new ExcelImFieldModel("sort", "该层排序"));
            columns.add(new ExcelImFieldModel("tableField116", "设计子表", tableField116columns));
            headAndDataMap.put("dataRow", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(excelDataList)));
            headAndDataMap.put("headerRow", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(columns)));
        } catch (Exception e) {
            e.printStackTrace();
            return ActionResult.fail("表头名称不可更改,表头行不能删除");
        }
        return ActionResult.success(headAndDataMap);
    }

    /**
     * 导入数据
     *
     * @return
     */
    @Operation(summary = "导入数据")
    @PostMapping("/ImportData")
    public ActionResult<ExcelImportModel> ImportData(@RequestBody VisualImportModel visualImportModel) throws Exception {
        List<Map<String, Object>> listData = new ArrayList<>();
        for (Map<String, Object> map : visualImportModel.getList()) {
            listData.add(map);
        }
        ImportFormCheckUniqueModel uniqueModel = new ImportFormCheckUniqueModel();
        uniqueModel.setDbLinkId(ThemeConstant.DBLINKID);
        uniqueModel.setUpdate(Objects.equals("1", "2"));
        ExcelImportModel excelImportModel = generaterSwapUtil.importData(ThemeConstant.getFormData(), listData, uniqueModel, ThemeConstant.TABLEFIELDKEY, ThemeConstant.getTableList());
        List<ImportDataModel> importDataModel = uniqueModel.getImportDataModel();
        for (ImportDataModel model : importDataModel) {
            String id = model.getId();
            Map<String, Object> result = model.getResultData();
            if (StringUtil.isNotEmpty(id)) {
                update(id, JsonUtil.getJsonToBean(result, ThemeForm.class), true);
            } else {
                create(JsonUtil.getJsonToBean(result, ThemeForm.class));
            }
        }
        return ActionResult.success(excelImportModel);
    }

    /**
     * 导出异常报告
     *
     * @return
     */
    @Operation(summary = "导出异常报告")
    @PostMapping("/ImportExceptionData")
    public ActionResult<DownloadVO> ImportExceptionData(@RequestBody VisualImportModel visualImportModel) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ThemeExcelErrorVO> themeVOList = JsonUtil.getJsonToList(visualImportModel.getList(), ThemeExcelErrorVO.class);
        UserInfo userInfo = userProvider.get();

        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            ExportParams exportParams = new ExportParams(null, "错误报告");
            exportParams.setType(ExcelType.XSSF);
            workbook = ExcelExportUtil.exportExcel(exportParams, ThemeExcelErrorVO.class, themeVOList);

            String fileName = "错误报告" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ActionResult.success(vo);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids) {
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i = 0;
        for (String allId : idList) {
            this.deleteAll(allId);
            i++;
        }
        if (i == 0) {
            return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 编辑
     *
     * @param id
     * @param themeForm
     * @return
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ThemeForm themeForm, @RequestParam(value = "isImport", required = false) boolean isImport) {
        themeForm.setId(id);
        if (!isImport) {
            String b = themeService.checkForm(themeForm, 1);
            if (StringUtil.isNotEmpty(b)) {
                return ActionResult.fail(b);
            }
        }
        ThemeEntity entity = themeService.getInfo(id);
        if (entity != null) {
            try {
                themeService.saveOrUpdate(themeForm, id, false);
            } catch (Exception e) {
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ThemeEntity entity = themeService.getInfo(id);
        if (entity != null) {
            //主表数据删除
            themeService.delete(entity);
            QueryWrapper<ThemeTreeEntity> queryWrapperThemeTree = new QueryWrapper<>();
            queryWrapperThemeTree.lambda().eq(ThemeTreeEntity::getThemeid, entity.getId());
            //子表数据删除
            themeTreeService.remove(queryWrapperThemeTree);
        }
        return ActionResult.success("删除成功");
    }

    @Operation(summary = "删除所有版本")
    @DeleteMapping("/deleteAll/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ActionResult deleteAll(@PathVariable("id") String id) {
        // 1. 获取当前主题版本信息
        ThemeEntity entity = themeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("主题版本不存在");
        }

        // 2. 获取所有关联版本ID（包括初始版本和衍生版本）
        Set<String> versionIds = new HashSet<>();
        versionIds.add(entity.getId());

        // 3. 如果存在初始版本，添加到删除集合
        if (StringUtil.isNotEmpty(entity.getFirstversion())) {
            versionIds.add(entity.getFirstversion());
        }

        // 4. 查找所有衍生版本
        QueryWrapper<ThemeEntity> versionWrapper = new QueryWrapper<>();
        versionWrapper.lambda().eq(ThemeEntity::getFirstversion, entity.getId());
        List<ThemeEntity> derivedVersions = themeService.list(versionWrapper);
        derivedVersions.forEach(v -> versionIds.add(v.getId()));

        // 5. 批量删除所有关联版本
        try {
            for (String versionId : versionIds) {
                // 删除主表数据
                themeService.delete(new ThemeEntity(versionId));

                // 删除关联的子表数据
                QueryWrapper<ThemeTreeEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(ThemeTreeEntity::getThemeid, versionId);
                themeTreeService.remove(queryWrapper);
            }
        } catch (Exception e) {
            // 出现异常，事务会回滚
            return ActionResult.fail("删除主题失败：" + e.getMessage());
        }

        return ActionResult.success("删除主题成功");
    }

    /**
     * 表单信息(详情页)
     * 详情页面使用-转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id) {
        ThemeEntity entity = themeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> themeMap = JsonUtil.entityToMap(entity);
        themeMap.put("id", themeMap.get("id"));
        //副表数据
        //子表数据
        List<ThemeTreeEntity> themeTreeList = themeService.getThemeTreeList(entity.getId(), "0");
        themeMap.put("tableField116", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(themeTreeList)));
        themeMap = generaterSwapUtil.swapDataDetail(themeMap, ThemeConstant.getFormData(), "690203104309691461", false);
        return ActionResult.success(themeMap);
    }

    /**
     * 获取详情(编辑页)
     * 编辑页面使用-不转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id) {
        ThemeEntity entity = themeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> themeMap = JsonUtil.entityToMap(entity);
        themeMap.put("id", themeMap.get("id"));
        //副表数据
        //子表数据
        List<ThemeTreeEntity> themeTreeList = themeService.getThemeTreeList(entity.getId(), "0");
        themeMap.put("themeTreeList", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(themeTreeList)));
        themeMap = generaterSwapUtil.swapDataForm(themeMap, ThemeConstant.getFormData(), ThemeConstant.TABLEFIELDKEY, ThemeConstant.TABLERENAMES);
        return ActionResult.success(themeMap);
    }

    @Operation(summary = "更改主题状态")
    @PutMapping("/changeStatus/{id}/{status}")
    public ActionResult changeStatus(@PathVariable("id") String id, @PathVariable("status") String status) {
        ThemeEntity entity = themeService.getInfo(id);
        return themeService.updateStatus(entity, status);

    }

    @Operation(summary = "获取主题树")
    @GetMapping("/getTree/{id}/{isPublish}")
    public ActionResult getThemeTree(@PathVariable("id") String id, @PathVariable("isPublish") String isPublish) {
        return ActionResult.success(themeService.getThemeTree(id, isPublish,false));
    }

    /**
     * 保存子表数据
     */
    @Operation(summary = "保存或发布")
    @PostMapping("/saveTree/{themeId}/{status}")
    public ActionResult<String> saveTree(@RequestBody @Valid List<TreeSaveDTO> treeSaveDTOList, @PathVariable("themeId") String themeId, @PathVariable("status") String status) {
        return themeTreeService.getStringActionResult(treeSaveDTOList, themeId, status);
    }

    /**
     * 获取主题列表
     */
    @Operation(summary = "获取主题版本列表")
    @PostMapping("/getThemeVersionList")
    public ActionResult<MyPageListVO<ThemeEntity>> getThemeVersionList(@RequestBody ThemeQueryReq themeQueryReq) {
        return themeService.getThemeVersionList(themeQueryReq);
    }

    @Operation(summary = "更改主题版本")
    @PutMapping("/setMainVersion/{themeId}")
    public ActionResult setMainVersion(@PathVariable("themeId") String themeId) {
        return themeService.setMainVersion(themeId);
    }

    /**
     * 获取主题详情
     */
    @Operation(summary = "获取主题版本详情")
    @GetMapping("/getThemeVersionInfo/{themeId}")
    public ActionResult<ThemeVersionInfoResp> getThemeVersionInfo(@PathVariable("themeId") String themeId) {
        return themeService.getThemeVersionInfo(themeId);
    }

    /**
     * 获取主题对比数据
     */
    @Operation(summary = "获取主题对比数据")
    @GetMapping("/getPkData")
    public ActionResult<List<ThemePkDTO>> getThemeVersionInfo() {
        return themeService.getPkData();
    }


    @Operation(summary = "通过id查询主题版本详情")
    @PostMapping("/getThemeVersionByIds")
    public ActionResult<ArrayList<ThemePkDataDTO>> getThemeVersion(@RequestBody List<ThemePkDataDTO> themeIds) {
        return themeService.getThemeVersion(themeIds);
    }

    @Operation(summary = "根据id列表获取总树")
    @PostMapping("/mergeTree")
    public ActionResult<List<TreeVO>> getMainThemeVersions(@RequestBody List<String> themeIds) {
        List<TreeVO> allTreeNodes = new ArrayList<>();
        for (String themeId : themeIds) {
            List<TreeVO> themeTree = themeService.getThemeTree(themeId, "1",true);
            allTreeNodes.addAll(themeTree);
        }
        return ActionResult.success(allTreeNodes);
    }

    @Operation(summary = "获取主版本的总树结构")
    @GetMapping("/mainThemeTree")
    public ActionResult<TreeVO> getMainThemeTree() {
        // 获取所有主版本的ID列表
        QueryWrapper<ThemeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ISMAIN", 1).ne("themeStatus","2").isNotNull("VERSION").select("ID");
        List<String> mainThemeIds = themeService.list(queryWrapper).stream().map(ThemeEntity::getId).collect(Collectors.toList());

        // 获取所有树的节点
        List<TreeVO> themeTree = themeService.getMergedThemeTree(mainThemeIds, "1");

        // 递归设置 objCount
        setObjCountRecursively(themeTree);

        // 构建树结构
        TreeVO root = new TreeVO();
        root.setId("root");
        root.setChildren(themeTree);
        return ActionResult.success(root);
    }



    @Operation(summary = "获取主题的主版本列表")
    @GetMapping("/mainThemeVersions")
    public ActionResult<List<Map<String, Object>>> getMainThemeVersions() {
        // 构建查询条件，筛选 ismain 为 1 的记录
        QueryWrapper<ThemeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ISMAIN", 1);
        // 指定要查询的字段
        queryWrapper.select("ID", "THEMENAME", "THEMETYPE", "VERSION", "FIRSTVERSION");

        // 执行查询
        List<ThemeEntity> themeEntities = themeService.list(queryWrapper);

        // 转换结果
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (ThemeEntity entity : themeEntities) {
            Map<String, Object> themeInfo = new HashMap<>();
            themeInfo.put("id", entity.getId());
            themeInfo.put("themename", entity.getThemename());
            themeInfo.put("themetype", entity.getThemetype());
            themeInfo.put("version", entity.getVersion());
            themeInfo.put("firstversion", entity.getFirstversion());
            resultList.add(themeInfo);
        }

        return ActionResult.success(resultList);
    }


    @Operation(summary = "根据主题ID查询文件列表")
    @PostMapping("/getThemeFiles")
    public ActionResult<MyPageListVO> getThemeFiles(@RequestBody ThemeDataReq req) {
        // 构建查询条件
        QueryWrapper<ThemeFileEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(req.getThemeName())) {
            // 从file_mange表中查询文件名称
            QueryWrapper<FileMangeEntity> fileMangeQueryWrapper = new QueryWrapper<>();
            fileMangeQueryWrapper.like("name", req.getThemeName());
            List<FileMangeEntity> fileMangeList = fileMangeService.list(fileMangeQueryWrapper);
            if (!fileMangeList.isEmpty()) {
                List<String> fileIds = fileMangeList.stream().map(FileMangeEntity::getId).collect(Collectors.toList());
                queryWrapper.in("fileid", fileIds);
            } else {
                return buildEmptyPageResult(req);
            }
        }

        if (StringUtil.isNotEmpty(req.getThemeId())) {
            queryWrapper.eq("themeid", req.getThemeId());
        }
        if (StringUtil.isNotEmpty(req.getNodeId())) {
            queryWrapper.eq("nodeid", req.getNodeId());
        }

        // 分页查询
        Page<ThemeFileEntity> page = new Page<>(req.getCurrentPage(), req.getPageSize());
        IPage<ThemeFileEntity> themeFilePage = themeFileService.page(page, queryWrapper);

        // 提取所有文件ID
        List<String> fileIds = themeFilePage.getRecords().stream()
                .map(ThemeFileEntity::getFileid)
                .collect(Collectors.toList());

        // 批量查询文件信息并建立映射关系
        Map<String, FileMangeEntity> fileMap = new HashMap<>();
        Map<String, KnowMangeEntity> knowMap = new HashMap<>();
        if (!fileIds.isEmpty()) {
            List<FileMangeEntity> fileEntities = fileMangeService.listByIds(fileIds);
            fileEntities.forEach(file -> fileMap.put(file.getId(), file));

            // 批量查询数据集信息并建立映射关系
            List<String> knowIds = fileEntities.stream()
                    .map(FileMangeEntity::getKnowid)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if (!knowIds.isEmpty()) {
                List<KnowMangeEntity> knowEntities = knowMangeService.listByIds(knowIds);
                knowEntities.forEach(know -> knowMap.put(know.getId(), know));
            }
        }

        // 提取所有创建人ID
        List<String> createUserIds = themeFilePage.getRecords().stream()
                .map(ThemeFileEntity::getCreateuser)
                .collect(Collectors.toList());

        // 批量查询用户信息并建立映射关系
        Map<String, String> userRealNameMap = new HashMap<>();
        if (!createUserIds.isEmpty()) {
            List<UserEntity> userList = userService.getUserNameList(createUserIds);
            userList.forEach(user -> userRealNameMap.put(user.getId(), user.getRealName()));
        }

        ArrayList<String> errorIds = new ArrayList<>();

        String baseUrl = serverUrlUtil.getBaseUrl();

        // 转换结果并去重处理
        Map<String, Map<String, Object>> uniqueFileMap = new LinkedHashMap<>(); // 使用LinkedHashMap保持顺序
        boolean hasNodeIdCondition = StringUtil.isNotEmpty(req.getNodeId());
        String targetNodeId = req.getNodeId();

        for (ThemeFileEntity themeFile : themeFilePage.getRecords()) {
            String fileId = themeFile.getFileid();
            FileMangeEntity fileMange = fileMap.get(fileId);

            if (fileMange != null) {
                Map<String, Object> resultMap = JsonUtil.entityToMap(themeFile);
                resultMap.put("fileName", fileMange.getName());
                resultMap.put("fileId", fileMange.getId());
                resultMap.put("createDate", fileMange.getCreatetime());
                resultMap.put("knowUrl", KNOW_URL + fileMange.getDatasetid());
                resultMap.put("dataSetId", fileMange.getDatasetid());
                resultMap.put("ragFileId", fileMange.getRagfileid());
                resultMap.put("localurl", fileMange.getLocalurl());

                // 设置创建人姓名
                String realName = userRealNameMap.get(themeFile.getCreateuser());
                resultMap.put("createUser", realName);

                // 设置数据集名称
                KnowMangeEntity knowMange = knowMap.get(fileMange.getKnowid());
                if (knowMange != null) {
                    resultMap.put("dataSetName", knowMange.getName());
                }
                resultMap.put("id", themeFile.getId());

                // 处理去重逻辑
                if (hasNodeIdCondition && targetNodeId.equals(themeFile.getNodeid())) {
                    // 如果当前记录的nodeid与查询条件相同，则强制保留（即使已有相同fileId的记录）
                    uniqueFileMap.put(fileId, resultMap);
                } else {
                    // 否则只在fileId不存在时添加
                    uniqueFileMap.putIfAbsent(fileId, resultMap);
                }
            } else {
                errorIds.add(fileId);
            }
        }

        themeFileService.deleteByIds(errorIds);

        // 转换Map为List
        List<Map<String, Object>> fileList = new ArrayList<>(uniqueFileMap.values());

        // 返回分页结果
        return buildPageResult(themeFilePage, fileList);
    }
    private ActionResult<MyPageListVO> buildEmptyPageResult(ThemeDataReq req) {
        MyPageListVO vo = new MyPageListVO();
        vo.setList(new ArrayList<>());
        MyPageInfo pageInfo = new MyPageInfo();
        pageInfo.setTotal(0L);
        pageInfo.setCurrentPage(Long.valueOf(req.getCurrentPage()));
        pageInfo.setPageSize(Long.valueOf(req.getPageSize()));
        vo.setPagination(pageInfo);
        return ActionResult.success(vo);
    }

    private ActionResult<MyPageListVO> buildPageResult(IPage<ThemeFileEntity> page, List<Map<String, Object>> list) {
        MyPageListVO vo = new MyPageListVO();
        vo.setList(list);
        MyPageInfo pageInfo = new MyPageInfo();
        pageInfo.setTotal(page.getTotal());
        pageInfo.setCurrentPage(page.getCurrent());
        pageInfo.setPageSize(page.getSize());
        vo.setPagination(pageInfo);
        return ActionResult.success(vo);
    }

    private void setObjCountRecursively(List<TreeVO> nodes) {
        if (nodes == null) {
            return;
        }
        for (TreeVO node : nodes) {
            if (!"root".equals(node.getId())) {
                Long count;
                if (StringUtil.isNotEmpty(node.getUniqueId())) {
                    // 有 uniqueId 的通过 themeId 统计
                    count = themeFileService.getCountByThemeId(node.getThemeId());
                } else {
                    // 没有 uniqueId 的通过 id 统计
                    count = themeFileService.getCountById(node.getId());
                }
                node.setObjCount(count != null ? count.intValue() : 0);
            }
            // 递归处理子节点
            setObjCountRecursively(node.getChildren());
        }
    }

}
